package com.ys.peony.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader;
import com.yklab.library.refreshlayout.adapters.CommonRecyclerViewAdapter;
import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import com.yklab.library.refreshlayout.inter.OnClickCommonListener;
import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.PermissionCon;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseFragment;
import com.ys.peony.enums.BusinessDetailStatus;
import com.ys.peony.enums.SwipeDirect;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespBean;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.CarModel;
import com.ys.peony.model.JiekuanrenModel;
import com.ys.peony.model.JiekuanrenResp;
import com.ys.peony.model.UserModel;
import com.ys.peony.ui.activity.AppointListActivity;
import com.ys.peony.ui.activity.BackPatchListActivity;
import com.ys.peony.ui.activity.BusiLoanInfoActivity;
import com.ys.peony.ui.activity.CarPledgeActivity;
import com.ys.peony.ui.activity.ContractListActivity;
import com.ys.peony.ui.activity.DaiMianShenListActivity;
import com.ys.peony.ui.activity.JiekuanrenListActivity;
import com.ys.peony.ui.activity.MainActivity;
import com.ys.peony.ui.activity.MessageActivity;
import com.ys.peony.ui.activity.MianshengActivity;
import com.ys.peony.ui.activity.PatchListActivity;
import com.ys.peony.ui.widget.Divider;
import com.ys.peony.utils.ImageLoadUtils;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.StringUtils;
import com.ys.peony.utils.ToastUtils;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import com.yklab.library.refreshlayout.BGANormalRefreshViewHolder;
import com.yklab.library.refreshlayout.BGARefreshLayout;

import q.rorbin.badgeview.QBadgeView;

/**
 * describe:首页
 * author:czhang
 * date:2017/5/6 23:00
 */
public class HomeFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate,
        View.OnClickListener, OnClickCommonListener {
    private final static int FRESH_DURATION = 1000;

    @BindView(R.id.rl_recyclerview_refresh)
    BGARefreshLayout mRefreshLayout;
    @BindView(R.id.rv_recyclerview_data)
    RecyclerView mDataRv;
    @BindView(R.id.header)
    RecyclerViewHeader mHeader;
    @BindView(R.id.ll_headview)
    View headerView;

    CommonRecyclerViewAdapter mAdapter;
    //动作类型
    private int actionType = 0;
    //总页数
    private int toatalPage = 0;

    //设置图片集合
    String[] urls = {"file:///android_asset/banner1.png", "file:///android_asset/banner2.png", "file:///android_asset/banner3.png"};
    private MZBannerView banner;
    private LinearLayout jiekuanren;
    private LinearLayout appoint;
    private LinearLayout patch;
    private LinearLayout backpatch;
    private LinearLayout daimianshen;
    private LinearLayout pledge;
    private LinearLayout message;
    private LinearLayout miansheng;

    private List<JiekuanrenModel> mList;
    private LinearLayoutManager mLayoutManager;

    @Override
    public int getLayoutRes() {
        return R.layout.home_fragment;
    }

    @Override
    public void initView() {
        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getActivity().getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);
        }*/
        initBanner();
        userPermissionControl();
        initAdapter();
        //获取未读消息数
        getMessageCount();
        //请求数据
        getData();
    }

    private void initBanner() {
        banner = (MZBannerView) headerView.findViewById(R.id.banner);
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        int pWidth = wm.getDefaultDisplay().getWidth();
        ViewGroup.LayoutParams params = banner.getLayoutParams();
        params.height = 395 * pWidth / 750;
        banner.setLayoutParams(params);

        //设置图片加载器
        List list = Arrays.asList(urls);
        List arrayList = new ArrayList(list);
        banner.setIndicatorVisible(true);
        banner.setPages(arrayList, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
    }

    private void initAdapter() {
        mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mRefreshLayout.setDelegate(this);
        // 设置下拉刷新和上拉加载更多的风格;参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        mRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(getContext(), true));
        mList = new ArrayList<>();
        mAdapter = new CommonRecyclerViewAdapter<JiekuanrenModel>(getContext(), mList, R.layout.recycler_view_item) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {
                super.onBindViewHolder(holder, position);
                if (!isFooterView(position)) {
                    JiekuanrenModel model = mList.get(position);
                    View view = ((CommonRecyclerViewHolder) holder).getView(R.id.item_title_tv);
                    if (position == 0) {
                        view.setVisibility(View.VISIBLE);
                    } else {
                        view.setVisibility(View.GONE);
                    }
                    ((CommonRecyclerViewHolder) holder).setText(R.id.tv_name, StringUtils.isEmpty(model.getClientName()) ? "" : model.getClientName());
                    if (!StringUtils.listIsEmpty(model.getVehicleList())) {
                        CarModel carModel = model.getVehicleList().get(model.getVehicleList().size() - 1);
                        if (null != carModel) {
                            ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carNum, StringUtils.isEmpty(carModel.getPlate_number()) ? "" : carModel.getPlate_number());
                            ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carBrand, StringUtils.isEmpty(carModel.getBrand_name()) ? "" : carModel.getBrand_name());
                        } else {
                            ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carNum, "");
                            ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carBrand, "");
                        }
                    } else {
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carNum, "");
                        ((CommonRecyclerViewHolder) holder).setText(R.id.tv_carBrand, "");
                    }
                    ((CommonRecyclerViewHolder) holder).setText(R.id.tv_customerType, model.getClientClassfyName());
                    ((CommonRecyclerViewHolder) holder).setText(R.id.tv_businessType, BusinessDetailStatus.getStatus(model.getLoanStatus()));
                    ((CommonRecyclerViewHolder) holder).setText(R.id.tv_businessNum, model.getSerialNumber());
                }
            }
        };
        mAdapter.setOnClickListener(this);
        mAdapter.isHasFooter(true);
        mDataRv.addItemDecoration(new Divider(getContext()));
        mDataRv.setLayoutManager(mLayoutManager);
        mDataRv.setAdapter(mAdapter);
        mHeader.attachTo(mDataRv);
    }

    private void userPermissionControl() {
        jiekuanren = headerView.findViewById(R.id.jiekuanren);
        appoint = headerView.findViewById(R.id.appoint);
        patch = headerView.findViewById(R.id.patch);
        backpatch = headerView.findViewById(R.id.backpatch);
        daimianshen = headerView.findViewById(R.id.daimianshen);
        message = headerView.findViewById(R.id.message);
        pledge = headerView.findViewById(R.id.pledge);
        miansheng = headerView.findViewById(R.id.miansheng);
        jiekuanren.setOnClickListener(null);
        appoint.setOnClickListener(null);
        patch.setOnClickListener(null);
        backpatch.setOnClickListener(null);
        daimianshen.setOnClickListener(null);
        message.setOnClickListener(null);
        pledge.setOnClickListener(null);
        miansheng.setOnClickListener(null);

        jiekuanren.findViewById(R.id.jiekuanren_iv).setAlpha(0.5f);
        appoint.findViewById(R.id.appoint_iv).setAlpha(0.5f);
        patch.findViewById(R.id.patch_iv).setAlpha(0.5f);
        backpatch.findViewById(R.id.backpatch_iv).setAlpha(0.5f);
        daimianshen.findViewById(R.id.daimianshen_iv).setAlpha(0.5f);
        message.findViewById(R.id.message_iv).setAlpha(0.5f);
        pledge.findViewById(R.id.pledge_iv).setAlpha(0.5f);
        miansheng.findViewById(R.id.miansheng_iv).setAlpha(0.5f);

        String[] comparePermissions = getResources().getStringArray(R.array.permission_list);
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        if (userModel != null && userModel.getPermissions() != null && userModel.getPermissions().size() > 0) {
            List<String> permissions = userModel.getPermissions();
            for (int i = 0; i < permissions.size(); i++) {
                String permission = permissions.get(i);
                for (int j = 0; j < comparePermissions.length; j++) {
                    if (comparePermissions[j].equals(permission)) {
                        switch (permission) {
                            case PermissionCon.busiAppointmentAction_list:
                                appoint.setOnClickListener(this);
                                appoint.findViewById(R.id.appoint_iv).setAlpha(1);
                                ((TextView) appoint.findViewById(R.id.appoint_tv)).setTextColor(getResources().getColor(R.color.color_5f5f5f));
                                break;
                            case PermissionCon.busiLoanAction_list:
                                jiekuanren.setOnClickListener(this);
                                backpatch.setOnClickListener(this);
                                pledge.setOnClickListener(this);
                                jiekuanren.findViewById(R.id.jiekuanren_iv).setAlpha(1);
                                backpatch.findViewById(R.id.backpatch_iv).setAlpha(1);
                                pledge.findViewById(R.id.pledge_iv).setAlpha(1);
                                ((TextView) jiekuanren.findViewById(R.id.jiekuanren_tv)).setTextColor(getResources().getColor(R.color.color_5f5f5f));
                                ((TextView) backpatch.findViewById(R.id.backpatch_tv)).setTextColor(getResources().getColor(R.color.color_5f5f5f));
                                ((TextView) pledge.findViewById(R.id.pledge_tv)).setTextColor(getResources().getColor(R.color.color_5f5f5f));
                                break;
                            case PermissionCon.busiFaceAudit_list:
                                daimianshen.setOnClickListener(this);
                                daimianshen.findViewById(R.id.daimianshen_iv).setAlpha(1);
                                ((TextView) daimianshen.findViewById(R.id.daimianshen_tv)).setTextColor(getResources().getColor(R.color.color_5f5f5f));
                                message.setOnClickListener(this);
                                message.findViewById(R.id.message_iv).setAlpha(1);
                                ((TextView) message.findViewById(R.id.message_tv)).setTextColor(getResources().getColor(R.color.color_5f5f5f));

                                break;
                            case PermissionCon.busiPatchAction_list:
                                patch.setOnClickListener(this);
                                patch.findViewById(R.id.patch_iv).setAlpha(1);
                                ((TextView) patch.findViewById(R.id.patch_tv)).setTextColor(getResources().getColor(R.color.color_5f5f5f));
                                break;
                            case PermissionCon.busiLoanFree_list:
                                miansheng.setOnClickListener(this);
                                miansheng.findViewById(R.id.miansheng_iv).setAlpha(1);
                                ((TextView) miansheng.findViewById(R.id.miansheng_tv)).setTextColor(getResources().getColor(R.color.color_5f5f5f));
                                break;
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.start();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.pause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.jiekuanren://借款人
                gotoJiekuanren();
                break;
            case R.id.appoint://预约
                gotoAppoint();
                break;
            case R.id.patch://补件
                gotoPatch();
                break;
            case R.id.backpatch://打回补件
                gotoBackPatch();
                break;

            case R.id.daimianshen://待面审
                ((MainActivity) getActivity()).skipToTargetPage(DaiMianShenListActivity.class, null, SwipeDirect.DIRECT_LEFT);
                break;
            case R.id.message://客户签约列表
                ((MainActivity) getActivity()).skipToTargetPage(ContractListActivity.class, null, SwipeDirect.DIRECT_LEFT);
                break;
            case R.id.pledge: //抵押物列表
                ((MainActivity) getActivity()).skipToTargetPage(CarPledgeActivity.class, null);
                break;
            case R.id.miansheng: //免审上传
                ((MainActivity) getActivity()).skipToTargetPage(MianshengActivity.class, null);
                break;
            default:
                break;
        }

    }

    private void gotoJiekuanren() {
        ((MainActivity) getActivity()).skipToTargetPage(JiekuanrenListActivity.class, null, SwipeDirect.DIRECT_LEFT);
    }

    private void gotoAppoint() {
        ((MainActivity) getActivity()).skipToTargetPage(AppointListActivity.class, null, SwipeDirect.DIRECT_LEFT);
    }

    private void gotoPatch() {
        ((MainActivity) getActivity()).skipToTargetPage(PatchListActivity.class, null, SwipeDirect.DIRECT_LEFT);
    }

    private void gotoBackPatch() {
        ((MainActivity) getActivity()).skipToTargetPage(BackPatchListActivity.class, null, SwipeDirect.DIRECT_LEFT);
    }


    /**
     * describe:获取数据
     * author:czhang
     * date:2017/5/29 16:31
     */
    private void getData() {
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        if (null == userModel) {
            ToastUtils.showToast("用户信息为空");
            return;
        }

        if (!NetUtils.isNetworkConnected(getBaseActivity())) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(userModel.getId()));
        params.put("currentPage", currentPage);
        params.put("pageNum", pageNum);
        httpManagerUtils.get(HttpURL.busiLoanPage, params, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                final JiekuanrenResp jiekuanrenResp = JSONUtil.parseObject(respStr, JiekuanrenResp.class);
                setData(jiekuanrenResp);
            }
        });
    }

    /**
     * describe:获取未读信息数量
     * author:czhang
     * date:2017/6/11 11:52
     */
    private void getMessageCount() {
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        if (null == userModel) {
            ToastUtils.showToast("用户信息为空");
            return;
        }
        if (!NetUtils.isNetworkConnected(getBaseActivity())) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(userModel.getId()));
        httpManagerUtils.get(HttpURL.getUserUnReadMessCount, params, new BaseRespCallBack(getBaseActivity()) {
            @Override
            public void onRespSuccess(String respStr) {
                final BaseRespBean baseRespBean = JSONUtil.parseObject(respStr, BaseRespBean.class);
                if (null != baseRespBean) {
                    String data = baseRespBean.getData().toString();
                    if (!data.equals("0")) {
                        QBadgeView qBadgeView = new QBadgeView(getBaseActivity());
                        qBadgeView.bindTarget(message).setBadgeNumber(Integer.parseInt(data));
                        qBadgeView.setBadgeGravity(Gravity.CENTER | Gravity.TOP);
                    }
                }
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                changeLoading(false);
                mRefreshLayout.endRefreshing();
            }
        });
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        actionType = YSConstant.ACTION_TYPE_DOWN;
        currentPage = 0;
        getData();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        actionType = YSConstant.ACTION_TYPE_UP;
        currentPage++;
        changeLoading(true);
        getData();
        return true;
    }

    /**
     * describe:设置数据
     * author:czhang
     * date:2017/6/24 10:51
     */
    private void setData(final JiekuanrenResp jiekuanrenResp) {
        switch (actionType) {
            case YSConstant.ACTION_TYPE_UP://上拉
                changeLoading(false);
                if (jiekuanrenResp != null && jiekuanrenResp.getDataList() != null) {
                    final int size = mList.size();
                    mList.addAll((jiekuanrenResp.getDataList()));
                    mAdapter.notifyItemRangeInserted(size, mList.size());
                }
                break;
            case YSConstant.ACTION_TYPE_DOWN://下拉刷新
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRefreshLayout.endRefreshing();
                        if (jiekuanrenResp != null && jiekuanrenResp.getDataList() != null) {
                            mList.clear();
                            mList.addAll(jiekuanrenResp.getDataList());
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }, FRESH_DURATION);
                break;
            default:
                if (jiekuanrenResp != null && jiekuanrenResp.getDataList() != null) {
                    toatalPage = null != jiekuanrenResp ? jiekuanrenResp.getPageCount() : 0;
                    mList.clear();
                    mList.addAll(jiekuanrenResp.getDataList());
                    mAdapter.notifyDataSetChanged();
                }
                break;
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

    }

    @Override
    public void onClickListener(View view, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("loanModel", mList.get(position));
        bundle.putString("fileType", "1");
        skipToTargetPage(BusiLoanInfoActivity.class, bundle);
    }

    final static class BannerViewHolder implements MZViewHolder<String> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局文件
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, String data) {
            // 数据绑定
            ImageLoadUtils.showImg(mImageView, data);
        }
    }

    private void changeLoading(boolean loading) {
        if (mAdapter != null) {
            mAdapter.setLoadingStatus(loading);
        }

    }
}
